package com.goldenautumn.prefabricate.activity.mine.address

import android.content.Intent
import android.view.animation.AnimationUtils
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.VibrateUtils
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.mine.adapter.AddressAdapter
import com.goldenautumn.prefabricate.business.entity.AddressInfoVo
import com.goldenautumn.prefabricate.business.user.LoadingUiState
import com.goldenautumn.prefabricate.business.user.LoginUiState
import com.goldenautumn.prefabricate.business.user.UserAddressUiState
import com.goldenautumn.prefabricate.business.user.UserViewModel
import com.goldenautumn.prefabricate.databinding.ActivityAddressManageBinding
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.goldenautumn.prefabricate.utils.onCenterToast
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseActivity
import qncx.external.common.compat.gone
import qncx.external.common.compat.isVisible
import qncx.external.common.utils.intent
import qncx.external.common.widget.dialog.PromptDialog
import qncx.external.common.widget.shapeview.shape.ShapeButton

class AddressManageActivity : BaseActivity<ActivityAddressManageBinding>() {

    private val mUserModel by viewModels<UserViewModel>()

    private val mAdapter by lazy {
        AddressAdapter()
    }

    private val addressID:Int
        get() = intent.getIntExtra(BUSINESS_PAGE_DATA,-1)

    override fun getLayoutId(): Int = R.layout.activity_address_manage

    override suspend fun main() {
        ImmersionBar.setTitleBar(this, mBinding.toolbar)
        initToolbarNav(mBinding.toolbar)
        mAdapter.selectPosition = addressID
        mBinding.addressRv.layoutManager = LinearLayoutManager(this)
        mBinding.addressRv.adapter = mAdapter
        mAdapter.setStateViewLayout(this,R.layout.recycler_empty_view)
        mAdapter.isStateViewEnable = true
        var msg = mAdapter.stateView?.findViewById<TextView>(R.id.prompt_content)
        msg?.text = getString(R.string.not_address)
        msg?.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.mipmap.ic_empty_address), null, null)

        mBinding.shapeLinearLayout4.isVisible(addressID >= 0)

        mBinding.actionBtn.setOnClickListener {
            if(addressID >= 0 && mAdapter.selectPosition > 0) {
                var item = mAdapter.items.findLast { it.address_id == mAdapter.selectPosition }
                var datas = Intent()
                datas.putExtra(BUSINESS_PAGE_DATA,item)
                setResult(RESULT_OK,datas)
                onBackPressedDispatcher.onBackPressed()
            } else {
                VibrateUtils.vibrate(50)
                mBinding.actionBtn.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake_anim))
            }
        }

        mAdapter.addOnItemChildClickListener(R.id.selectBtn){ adapter,_,position ->
            adapter.items.forEach { it.isDefault = false }
            var item = adapter.getItem(position)
            item?.isDefault = true
            adapter.notifyDataSetChanged()
            mUserModel.onDefaultAddress("${item?.address_id}")
        }

        mAdapter.addOnItemChildClickListener(R.id.editBtn){ adapter,_,position ->
            var item = adapter.getItem(position)
            startActivity(AddressEditActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,item))
        }

        mAdapter.addOnItemChildClickListener(R.id.deleteBtn){ adapter,_,position ->
            var item = adapter.getItem(position)
            PromptDialog().setConfirmListener(object : PromptDialog.ConfirmHandleListener{
                override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                    view.setShowCancel(true)
                    view.setTitleText(getString(R.string.delete_address))
                    view.setMsgText(getString(R.string.delete_address_content))
                    view.setConfirmText(getString(R.string.delete))
                    view.getPromptConfirm().setTextColor(ContextCompat.getColor(this@AddressManageActivity,R.color.color_DE0000))
                    view.getPromptConfirm().setOnClickListener {
                        dialog.dismiss()
                        adapter.removeAt(position)
                        adapter.notifyItemChanged(position)
                        mUserModel.onDeleteAddress("${item?.address_id}")
                    }
                }
            }).onShow(supportFragmentManager.beginTransaction())
        }

        mAdapter.setOnItemClickListener{ adapter,_,position ->
            if(addressID >= 0){
                var item = adapter.getItem(position)
                mAdapter.selectPosition = "${item?.address_id}".toInt()
                mAdapter.notifyDataSetChanged()
                mUserModel.onDefaultAddress("${item?.address_id}")
            }
        }

        mBinding.newBtn.setOnClickListener { startActivity(AddressEditActivity::class.intent) }

        while (isActive) {
            select {
                mUserModel.loading.onReceive {
                    when(it) {
                        is LoadingUiState.LoadingUI -> {
                            if(!it.isShow) mBinding.loading.appName.gone()
                            else {}
                        }
                        else -> {}
                    }
                }
                mUserModel.addressUiState.onReceive {
                    when(it) {
                        is UserAddressUiState.AddressList -> {
                            mAdapter.submitList(it.addressList)
                        }
                        is UserAddressUiState.AddressAction -> {
//                            if(!it.isSuccess) onCenterToast("${it.msg}")
//                            else onCenterToast(getString(R.string.operation_success))
                        }
                        else -> {}
                    }
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        mUserModel.getAddressList()
    }

}